package com.qf.shop.controller;

import com.qf.shop.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

@WebServlet(name = "BaseController")//反射方法
public class BaseController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求的方法  method
        String method = request.getParameter("method");
        System.out.println(method);
        //根据请求传递的方法名，直接调用对应的方法。。省去判断
        //反射
        //1.获取类对象
        Class aClass = this.getClass();
        try {
            Method method1  = aClass.getMethod(method,HttpServletRequest.class,HttpServletResponse.class);
            //3.通过反射进行执行方法
            String result= (String)method1.invoke(this,request,response);
            if(result!=null&&result.trim().length()!=0){
                 //redirect:/registerSuccess.jsp
                if(result.startsWith(Constants.FORWARD)){
                    //截取返回结果字符串中要跳转的路径。  /....jsp
                    String path = result.substring(result.indexOf(":")+1);
                    System.out.println(path);
                    request.getRequestDispatcher(path).forward(request,response);
                }else if (result.startsWith(Constants.REDIRECT)){
                    //截取返回结果字符串中要跳转的路径。  /....jsp
                    String path = result.substring(result.indexOf(":")+1);
                    //   项目名/registerSuccess.jsp
                    response.sendRedirect(request.getContextPath()+path);
                }else{
                    response.getWriter().print(result);
                }
            }
        } catch (Exception e) {
            System.out.println("反射获取方法是出现异常！");
            e.printStackTrace();
        }


    }
}
